#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

const int gdefaultfd = -1;

#define EPSERVERNUM 1024

class EpollServer
{

public:
    EpollServer(int port)
        : _port(port),
          _isrunning(false),
          _listen_socket(std::make_unique<TcpSocket>(port))
    {
    }

    void Init()
    {
        // 初始化辅助数组 建立tcp监听
        _listen_socket->BuildTcpSocketMethod(_port);

        _epfd = epoll_create(20);
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_create failed";
            DIE(EPOLL_CREATE_ERROR);
        }

        // 添加listen监听
        struct epoll_event event;
        event.events = EPOLLIN | EPOLLET;
        event.data.fd = _listen_socket->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->Fd(), &event);

        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl failed";
            DIE(EXIT_FAILURE);
        }
    }

    void Loop()
    {
        _isrunning = true;

        while (_isrunning)
        {
            // 2.开始监测    函数执行前用于用户通知内核的信息 执行完毕后为内核通知用户的信息
            int n = epoll_wait(_epfd, _revs, EPSERVERNUM, -1);

            if (n > 0)
            {
                std::cout << "有事件就绪啦... " << std::endl;
                Dispatcher(n); // 把已经就绪的sockfd，派发给指定的模块
            }
            else if (n == 0)
            {
                std::cout << "时间结束，没有时间就绪" << std::endl;
            }
            else
            {
                LOG(LogLevel::ERROR) << "poll failed";
                break;
            }
        }

        _isrunning = false;
    }

    void Accepter()
    {
        // 有新的连接要accept
        InetAddr client;
        int newsockfd = _listen_socket->Accepter(&client);
        if (newsockfd < 0)
        {
            LOG(LogLevel::ERROR) << "Accepter failed";
            return;
        }

        LOG(LogLevel::DEBUG) << "获得一个新连接 sockfd:" << newsockfd << "地址为:" << client.Addr();

        // 加入Epoll中
        epoll_event ev;
        ev.data.fd = newsockfd;
        ev.events = EPOLLIN;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newsockfd, &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl failed";
            DIE(EXIT_FAILURE);
        }
    }

    void Recver(int who)
    {
        // 读事件就绪 读取内容并且返回给用户
        int fd = _revs[who].data.fd;
        char buffer[1024];
        int n = read(fd, buffer, sizeof(buffer) - 1); // 完整性暂且不管

        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer;
            std::string result = "echo #";
            result += buffer;
            write(fd, result.c_str(), result.size());
        }
        else if (n == 0)
        {
            // 写端关闭
            LOG(LogLevel::DEBUG) << fd << "写端关闭退出";

            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl failed";
                DIE(EXIT_FAILURE);
            }

            close(fd); // 关闭文件
        }
        else
        {
            LOG(LogLevel::DEBUG) << fd << "读取错误";
            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl failed";
                DIE(EXIT_FAILURE);
            }
            close(fd); // 关闭文件
        }
    }

    void Dispatcher(int n)
    {
        for (int i = 0; i < n; i++)
        {
            // 文件描述符，先得是合法的
            if (_revs[i].data.fd == _listen_socket->Fd())
            {
                if (_revs[i].events & EPOLLIN)
                {
                    Accepter(); // 连接的获取
                }
            }
            else
            {
                if (_revs[i].events & EPOLLIN)
                {
                    Recver(i); // IO的处理
                }
            }
        }
    }

    ~EpollServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;

    int _epfd;
    struct epoll_event _revs[EPSERVERNUM];
};
